var app = global.app;
var rootPath = app.rootPath;
var filePath = app.filePath;
var models = require(rootPath + '/models/index.js');
var mediaModel = models['media'];
var md5 = require(rootPath + '/tool/md5.js').md5;
var child_process = require('child_process');
var spawn = child_process.spawn;
var Q = require(rootPath + '/tool/taskQueue.js');
var downFile = require(rootPath + '/tool/downFile.js');
var getImageInfo = require(rootPath + '/tool/getImageInfo.js');
var save2oss = require(rootPath + '/tool/save2oss.js');
var action = function (req, res) {
    var url = req.param('url');
    console.log(url);
    if (!url) {
        res.jsonp({
            'type':'error',
            'message':'arguments error'
        });
        return;
    }
    var id = md5(url);
    var q = new Q();
    var ret = {};
    q.add(function (resp, next) {
        mediaModel.findById(id, function (err, doc) {
            if (err) {
                res.jsonp(err);
                q = null;
                return;
            }
            if (doc == null) {
                next();
            } else {
                res.jsonp(doc);
                q = null;
            }
        });
    });
    q.add(function (resp, next) {
        downFile(url, md5(url), function (_ret) {
            if (_ret.error) {
                res.jsonp(_ret);
                q = null;
                return;
            }
            ret.mix(_ret.data);
            next();
        });
    });
    q.add(function (resp, next) {
        getImageInfo(ret.fileName, function (_ret) {
            if (_ret.error) {
                res.jsonp(_ret);
                q = null;
                return;
            }
            ret.mix(_ret.data);
            next();
        });
    });
    q.add(function (resp, next) {
        save2oss(ret.fileName, 'source/' + ret.fileName, function (_ret) {
            if (_ret.error) {
                res.jsonp(_ret);
                q = null;
                return;
            }
            spawn('rm', [filePath + ret.fileName, '-rf']);
            ret.mix(_ret.data);
            next();
        });
    });
    q.add(function (resp, next) {
        ret._id = ret.fileName.split('.')[0];
        var media = new mediaModel();
        media.mix(ret);
        media.save(function (err, doc) {
            if (err) {
                res.jsonp(err);
                q = null;
                return;
            }
            ret = doc;
            next();
        });
    });
    q.add(function (resp, next) {
        res.jsonp(ret);
        q = null;
    });
    q.next();
};
app.get('/url/:url', action);
app.get('/', action);